package cn.yc.reader;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class FileReader_ {
    public static void main(String[] args) {
    }

    @Test
    public void test01() {
        String filePath = "e:\\io\\story.txt";
        FileReader fileReader = null;
        int data = 0;
        try {
            fileReader = new FileReader(filePath);
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

    @Test
    public void test02() {
        String filePath = "e:\\io\\story.txt";
        FileReader fileReader = null;
        int readLength = 0;
        char[] buf = new char[1024]; // 数组长度自拟
        try {
            fileReader = new FileReader(filePath);
            // 循环读取并输出  批量读取 read(buf)返回的是实际读取到的字符数
            // 如果返回 -1，说明文件读取结束
            while ((readLength = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLength));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
